package com.yuwei.yurpc.server;

import com.yuwei.yurpc.RpcApplication;
import com.yuwei.yurpc.config.RpcConfig;
import com.yuwei.yurpc.model.RpcRequest;
import com.yuwei.yurpc.model.RpcResponse;
import com.yuwei.yurpc.registry.LocalRegistry;
import com.yuwei.yurpc.serializer.JdkSerializer;
import com.yuwei.yurpc.serializer.Serializer;
import com.yuwei.yurpc.serializer.SerializerFactory;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;

/**
 * 用户服务
 *
 * @author yuwei
 * @date 15:59 2024/10/3
 */
public class HttpServerHandler implements Handler<HttpServerRequest> {
    @Override
    public void handle(HttpServerRequest httpServerRequest) {
        final Serializer serializer = SerializerFactory.getInstance(RpcApplication.getRpcConfig().getSerializerKey());
        //记录日志
        System.out.println("收到请求"+httpServerRequest.uri());
        //异步处理
        httpServerRequest.bodyHandler(body -> {
            byte[] bytes = body.getBytes();
            RpcRequest rpcRequest = null;
            try{
                rpcRequest = (RpcRequest) serializer.deserialize(bytes,RpcRequest.class);
            } catch (IOException e) {
               e.printStackTrace();

            }
            RpcResponse rpcResponse = new RpcResponse();
            if(rpcRequest ==null){
                rpcResponse.setMessage("反序列化失败");
                doResponse(httpServerRequest,rpcResponse,serializer);
                return;
            }
            try{
                Class<?> clazz = LocalRegistry.get(rpcRequest.getServiceName());
                Method method = clazz.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
                Object result = method.invoke(clazz.newInstance(), rpcRequest.getArgs());
                rpcResponse.setData(result);
                rpcResponse.setDataType(method.getReturnType());
                rpcResponse.setMessage("ok");

            }catch (Exception e){
                e.printStackTrace();
                rpcResponse.setMessage("调用失败");
                rpcResponse.setException(e);
            }
                doResponse(httpServerRequest,rpcResponse,serializer);
        });

    }
    void doResponse(HttpServerRequest request, RpcResponse rpcResponse, Serializer serializer) {
        HttpServerResponse response = request.response();
        response.putHeader("content-type", "application/json");
        try {
            byte[] bytes = serializer.serialize(rpcResponse);
            response.end(Buffer.buffer(bytes));
        } catch (Exception e) {
            e.printStackTrace();
            response.end(Buffer.buffer());
        }

    }
}
